package com.chat.api.web.service;

import com.chat.api.common.exception.ApiException;
import com.chat.api.utils.ResultUtil;
import com.chat.api.utils.util.DateUtil;
import com.chat.api.utils.util.IdWorkerUtil;
import com.chat.api.web.dao.ChatRepo;
import com.chat.api.web.po.BlogBean;
import com.chat.api.web.po.ChatBean;
import com.chat.api.web.po.UserBean;
import com.chat.api.web.restctrl.WebSocketServer;
import com.chat.api.web.vo.ChatEntity;
import com.chat.api.web.vo.MessageEntity;
import com.chat.api.websocket.MyWebSocket;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class ChatService {

    @Autowired
    private ChatRepo chatRepo;
    @Autowired
    private UserService userService;

    /**
     * 获取聊天记录
     *
     * @param receiver
     * @param request
     * @return
     */
    public MessageEntity getChatLog(Long receiver, HttpServletRequest request) {
        try {
            UserBean byUserInfo = userService.findByUserInfo(request);
            Long userId = byUserInfo.getId();
            List<ChatEntity> entities = Lists.newArrayList();
            List<ChatBean> beans = chatRepo.findByUidAndRid(userId,receiver);
            List<ChatBean> beans2 = chatRepo.findByRidAndUid(userId,receiver);
            beans.addAll(beans2);
            List<ChatBean> list = sortByDate(beans); //根据日期排序
            for (ChatBean bean : list) {
                ChatEntity chatEntity = new ChatEntity();
                chatEntity.setEntity(bean);
                entities.add(chatEntity);
            }
            chatRepo.updateNoRead(userId,receiver);
            return ResultUtil.success(entities);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.fail("获取聊天记录失败，请稍后再试!");
        }
    }

    private List<ChatBean> sortByDate(List<ChatBean> beans) {
        try {
            Collections.sort(beans, new Comparator<ChatBean>() {
                @Override
                public int compare(ChatBean o1, ChatBean o2) {
                    Long time1 = o1.getCreateDate().getTime();
                    Long time2 = o2.getCreateDate().getTime();
                    if (time1 > time2){
                        return 1;
                    }else if (time1 < time2){
                        return -1;
                    }else {
                        return 0;
                    }
                }
            });
            return beans;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("聊天记录排序失败！！！");
        }
    }

    /**
     *消息同步到数据库
     * @param rid
     * @param message
     * @param request
     * @return
     */
    @Transactional(readOnly = false)
    public MessageEntity saveMsg(Long rid, String message, HttpServletRequest request) {
        try {
            String trim = StringUtils.trim(message);
            if (StringUtils.isBlank(trim)){
                return ResultUtil.fail("内容不能为空");
            }
            MyWebSocket socket = new MyWebSocket();
//            socket.onMessage(message,);
            UserBean info = userService.findByUserInfo(request);
            ChatBean chatBean = new ChatBean();
            Long id = IdWorkerUtil.getInstance().nextId();
            chatBean.setId(id);
            chatBean.setReceiver(rid);
            chatBean.setIsRead(0);
            chatBean.setMessage(message);
            chatBean.setUserId(info.getId());
            chatBean.setCreateBy(info.getId());
            chatBean.setCreateDate(new Date());
            chatRepo.save(chatBean);
            UserBean receive = userService.findById(rid);
            socket.pushMessage(info.getName(), message, receive.getName());
            return ResultUtil.success("同步成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.fail("系统繁忙，请稍后再试！！！");
        }
    }

    //查询未读消息数
    public Integer findNoReadCount(Long userId, Long receiverId) {
        return chatRepo.findNoReadCountById(userId,receiverId);
    }

    //查询所有未读消息
    public MessageEntity getNoReadCount(HttpServletRequest request) {
        try {
            UserBean userBean = userService.findByUserInfo(request);
            Integer count = chatRepo.findAllNoReadCount(userBean.getId());
            if (count == 0){
                return ResultUtil.success(1);
            }
            return ResultUtil.success("有新消息：" + count + "条！");
        }catch (Exception e){
            return ResultUtil.fail("获取未读消息失败！！！");
        }
    }

    public MessageEntity getOnlineNum(){
        try {
            MyWebSocket myWebSocket = new MyWebSocket();
            int onlineNumber = myWebSocket.getOnlineNumber();
            return ResultUtil.success(onlineNumber);
        }catch (Exception e){
            return ResultUtil.fail("无");
        }
    }

    /**
     * 管理员发送通知
     * @param receiver
     * @param message
     */
    public void sendMsg(Long receiver, String message) {
        try {
            ChatBean chatBean = new ChatBean();
            Long id = IdWorkerUtil.getInstance().nextId();
            chatBean.setId(id);
            chatBean.setMessage(message);
            chatBean.setUserId(333L);
            chatBean.setReceiver(receiver);
            chatBean.setIsRead(0);
            chatBean.setCreateDate(new Date());
            chatBean.setCreateBy(333L);
            chatRepo.save(chatBean);
        }catch (Exception e){
            throw new ApiException("博客审批完成通知异常： " + e);
        }
    }

    /**
     * 游客联系站主
     * @param request
     * @param fullname
     * @param email
     * @param iphoneNumber
     * @param message
     * @return
     */
    public MessageEntity sendLT(HttpServletRequest request, String fullname, String email, String iphoneNumber, String message) {
        String trim = StringUtils.trim(message);
        message = "name:" + fullname + ",email:" + email + ",手机号：" + iphoneNumber + ",信息：" + message;
        if (StringUtils.isBlank(trim)){
            return ResultUtil.fail("内容不能为空");
        }
        MyWebSocket socket = new MyWebSocket();
//            socket.onMessage(message,);
        String name = "刘涛";
        String name2 = "网络管理员";
        UserBean info = userService.findByName(name);
        UserBean info2 = userService.findByName(name2);
        ChatBean chatBean = new ChatBean();
        Long id = IdWorkerUtil.getInstance().nextId();
        chatBean.setId(id);
        chatBean.setReceiver(info.getId());
        chatBean.setIsRead(0);
        chatBean.setMessage(message);
        chatBean.setUserId(info2.getId());
        chatBean.setCreateBy(info2.getId());
        chatBean.setCreateDate(new Date());
        chatRepo.save(chatBean);
        UserBean receive = userService.findById(info.getId());
        socket.pushMessage(info.getName(), message, receive.getName());
        return ResultUtil.success("同步成功");
    }

}
